package com.ruiben.mall.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class FileUploadUtils {

    /**
     * 保存文件，直接以multipartFile形式
     * @param multipartFile
     * @param path 文件保存绝对路径
     * @return 返回文件名
     * @throws IOException
     */
    public static String saveImg(MultipartFile multipartFile, String path) {
        String fileName = null;
        BufferedOutputStream bos = null;
        try {
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
            fileName = UUID.randomUUID().toString();
            bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
            byte[] bs = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
        } catch (Exception e) {
            return "";
        } finally {
            try {
                if (bos!=null){
                    bos.flush();
                    bos.close();
                }
            } catch (IOException e) {
                fileName = "";
            }
        }

        return fileName;
    }

}
